from kivy.logger import Logger
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.progressbar import ProgressBar
from nmjeditor.screens.screen import Screen
from nmjeditor.widgets.wall import ScrollableShowWall



class MainScreen(Screen):
	def __init__(self, screen_factory, controller):
		super(MainScreen, self).__init__(screen_factory, controller)
		self.root = GridLayout(size_hint = (1, 1), cols = 1, rows = 2)
		toolbar = GridLayout(cols=2, height=50, size_hint=(1, 0.25))
		self.progress_bar = ProgressBar()
		self.scan = Button(pos=(10, self.top - 60), width=200, height=50, text="Scan media...")
		self.scan.bind(on_press=self.on_scan)
		toolbar.add_widget(self.scan)
		toolbar.add_widget(self.progress_bar)
		self.scroll = ScrollableShowWall(size_hint=(1.0, 1.0), callback=self.show_choosen)
		self.root.add_widget(toolbar)
		self.root.add_widget(self.scroll)
		self.add_widget(self.root)
		self.scan_in_progress = False
		Logger.info("MainScreen created")

	def on_show_max(self, show_number):
		Logger.info("Set progress max to %d", show_number)
		if show_number:
			self.progress_bar.max = show_number
		self.progress_bar.value=0

	def on_show(self, show):
		self.scroll.add_shows(show)
		self.progress_bar.value += 1

	def on_scan(self, value):
		Logger.info("Start scan")
		if self.scan_in_progress:
			return
		self.scan_in_progress = True
		self.scan.text = "Scanning..."
		self.controller.update()

	def on_scan_progress(self, value):
		Logger.info("Scan rank = %d", value)
		self.progress_bar.value = value
		if self.progress_bar.value == self.progress_bar.max:
			self.scan.text = "Scan media..."
			self.scan_in_progress = False
			self.root.remove_widget(self.scroll)
			self.scroll = ScrollableShowWall(size_hint=(1.0, 1.0), callback=self.show_choosen)
			self.root.add_widget(self.scroll)
			self.controller.get_shows()


	def show_choosen(self, show):
		self.screen_factory.set_screen(show.title, show)


